using System.ComponentModel.DataAnnotations;

namespace Vin.Tool.Attributes.Validation;

public class ClearValueAttribute : ValidationAttribute
{
    public string[] ContainsFields { get; set; } = [];

    protected override ValidationResult? IsValid(object? value, ValidationContext? validationContext)
    {
        if (value == null || ContainsFields.Length <= 0 || validationContext == null)
            return ValidationResult.Success;

        foreach (var fieldName in ContainsFields)
        {
            if (validationContext.ObjectType.GetProperty(fieldName)?.GetValue(validationContext.ObjectInstance) != null)
            {
                validationContext.ObjectType.GetProperty(validationContext.DisplayName)
                    ?.SetValue(validationContext.ObjectInstance, null);
                break;
            }
        }

        return ValidationResult.Success;
    }
}